import Vue from 'vue'
import VueRouter from 'vue-router'
// 三种方式定位位置 import Login from '../components/Login.vue'
// import Login from '@/components/Login.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', name: 'Login', component: () => import('@/components/Login.vue') },
  {
    path: '/main',
    name: 'Main',
    component: () => import('../views/Main'),
    redirect: '/welcome', // 路由重定向 当访问/main->/welcome
    children: [
      { path: '/welcome', component: () => import('@/components/Welcome.vue') },
      { path: '/users', component: () => import('../views/user/Users') },
      { path: '/passwords', component: () => import('../views/user/Passwords') }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 挂载路由守卫 控制页面导航
router.beforeEach((to, from, next) => {
  // to 将要访问的路径 from 代表从哪个路径跳转而来 next 是一个函数表示放行 next() 强制放行next('/login')
  if (to.path === '/login') return next()
  // 获取token
  const token = window.sessionStorage.getItem('token')
  if (!token) return next('/login')
  next()
})

export default router
